package cz.stv;

import czStvDpds.logging.Logging;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Scanner;
import java.util.concurrent.LinkedTransferQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

/**
 *
 * @author Martin Strouhal
 */
public class ThreadReceiver extends Thread {

    private DatagramSocket datagramSocket;
    public static int RECEIVING_PORT = 9877;
    public static int MAX_SIZE_RECEIVED_DATA = 512;
    private static LinkedTransferQueue<DatagramPacket> queue;

    public ThreadReceiver(LinkedTransferQueue q) {
        try {
            datagramSocket = new DatagramSocket(RECEIVING_PORT);
        } catch (SocketException ex) {
            Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
        }
        queue = q;
    }

    @Override
    public void run() {
        int volbaPrijmu = 0; //0 = prijem od klienta, else = prijem z okna
        if (volbaPrijmu == 0) {            
            DatagramPacket datagramPacket;
            while (true) {
                datagramPacket = new DatagramPacket(new byte[MAX_SIZE_RECEIVED_DATA], MAX_SIZE_RECEIVED_DATA);
                try {
                    Logging.getMainLogger().log(Level.SEVERE, "SERVER:Cekam na paket");
                    datagramSocket.receive(datagramPacket);                    
                    Logging.getMainLogger().log(Level.SEVERE, "SERVER:Prijmut paket");
                    queue.add(datagramPacket);

                } catch (IOException ex) {
                    Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
                }
            }
        } else {
            JFrame frame = new JFrame("Server");
            JButton send = new JButton("Send");
            JTextField field = new JTextField(37);
            JTextPane history = new JTextPane();

            history.setEditable(false);

            send.addActionListener(new Listener(history, field, queue));

            frame.setLayout(new BorderLayout());
            frame.add(BorderLayout.CENTER, new JScrollPane(history));
            JPanel panel = new JPanel();
            panel.add(field);
            panel.add(send);
            frame.add(BorderLayout.SOUTH, panel);
            frame.setSize(500, 200);
            frame.setResizable(false);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    }
}